package com.njzxw.fs.commonutil.web;

import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

@RestController
@Controller
@RestControllerAdvice
@ControllerAdvice
@EnableConfigurationProperties(ServerProperties.class)
public class MainsiteErrorCommonController extends BaseController implements ErrorController,HandlerInterceptor{

    @Autowired
    private ErrorAttributes errorAttributes;

    @Autowired
    private ReturnMap returnMap;


    @Override
    public String getErrorPath() {
        return "/error";
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {

        if(response.getStatus() != 200){
            logger.error("服务器异常:"+response.getStatus());
            returnMap.setReturnMaps(ReturnMap.States.ERROR);
            returnMap.setDataMaps("服务器异常");
            modelAndView.addObject(JSONObject.fromObject(returnMap.getReturnMap()));
        }
    }

    @ExceptionHandler(value = Exception.class)
    public void error(Exception ex,HttpServletRequest request,HttpServletResponse response,ModelAndView modelAndView){
        logger.error("服务器异常",ex);
        if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
            this.writeJsonData(returnMap.getErrorReturnMap("服务器异常"),response);
        }else{
            this.writeJsonData(returnMap.getErrorReturnMap("服务器异常"),response);
        }
    }

    @RequestMapping("/error")
    public ModelAndView error(HttpServletResponse response,HttpServletRequest request){

//        Enumeration<String> enumeration = request.getAttributeNames();
//        while(enumeration.hasMoreElements()){
//            String key = enumeration.nextElement();
//            System.out.println(key+"--------------------"+request.getAttribute(key));
//        }
        Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");

        String uri = (String)request.getAttribute("javax.servlet.forward.request_uri");
        if(StringUtils.isBlank(uri)){
            uri = (String)request.getAttribute("javax.servlet.error.request_uri");
        }

        ModelAndView modelAndView = new ModelAndView();

        switch (statusCode){
            case HttpServletResponse.SC_UNAUTHORIZED:
            case HttpServletResponse.SC_NOT_FOUND:
            case HttpServletResponse.SC_FORBIDDEN:
                logger.error("错误请求页面："+uri+"错误码："+statusCode);
                if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
                    modelAndView.setView(new MappingJackson2JsonView());
                    modelAndView.addObject("state",ReturnMap.States.getValue(ReturnMap.States.ERROR_SERVER));
                    modelAndView.addObject("msg","服务器错误");
                }else{
                    modelAndView.setViewName("forward:/404.html");
                }
                break;
            case HttpServletResponse.SC_INTERNAL_SERVER_ERROR:
                Exception e = (Exception)request.getAttribute("javax.servlet.error.exception");
                logger.error("错误请求页面："+uri+"错误码：500，错误内容："+e.getMessage(),e);
                if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
                    modelAndView.setView(new MappingJackson2JsonView());
                    modelAndView.addObject("state",ReturnMap.States.getValue(ReturnMap.States.ERROR_SERVER));
                    modelAndView.addObject("msg","服务器错误");
                }else{
                    modelAndView.setViewName("forward:/error.html");
                }
                break;
            default:
                e = (Exception)request.getAttribute("javax.servlet.error.exception");

                logger.error("错误请求："+statusCode+" url:"+uri+" 请求类型："+request.getHeader("X-Requested-With"),e);
                if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
                    modelAndView.setView(new MappingJackson2JsonView());
                    modelAndView.addObject("state",ReturnMap.States.getValue(ReturnMap.States.ERROR_SERVER));
                    modelAndView.addObject("msg","服务器错误");
                }else{
                    modelAndView.setViewName("forward:/error.html");
                }
                break;

        }

        return modelAndView;

    }

}
